import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { SERVER_URL } from '../constant';
import BaseService from './base.service';
import { Token } from '../model/token';
import { TokenStorageService } from './storage.service';
@Injectable()
export class AuthService extends BaseService<Token> {

    constructor(public storageService: TokenStorageService, public http: HttpClient) {
        super(Token, 'auth', storageService, http);
    }

    async ping(token) : Promise<boolean> { 
        let result: any = await (this.http.post(this.resourceUrl + '/pong', null, {
            headers: {
                token,
            }
        }).toPromise());
        if (typeof result == 'string') { 
            result = JSON.parse(result);
        }
        let data = this.handleData(result);
        return (data.token == token);
    }

    async login(username: string, pwd: string): Promise<string | null> { 
        let url = this.resourceUrl + '/login'
        let p = this.http.post(url, {username, pwd}).toPromise();
        let result: any = await p;
        let data = this.handleData(result);
        return (data && data.token) || null;
    }

    async registry(username: string, pwd: string): Promise<boolean> { 
        let url = this.resourceUrl + '/registry';
        let p = this.http.post(url, { username, pwd }).toPromise();
        let result: any = await p;
        let data = this.handleData(result);
        return data && data.username == username;
    }
}
